package com.botarena.client.contest;

import java.util.Date;
import java.util.List;

import com.botarena.client.contest.remote.ContestAccess;
import com.botarena.client.contest.remote.ContestAccessAsync;
import com.botarena.shared.ContestInfo;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ContestEditor extends VerticalPanel {

	public ContestEditor() {
		setWidth("100%");
		//Label contestsLab = new Label("View existing contests");
		//contestsLab.setStyleName("comment");
		//add(contestsLab);
		Label status = new Label(); // TODO: add loading
		add(status);
		showContestData(status, this);
	}

	private void showContestData(final Label status, final Panel panel) {
		ContestAccessAsync daa = GWT.create(ContestAccess.class);
		daa.getAllContests(new AsyncCallback<List<ContestInfo>>() {

			@Override
			public void onFailure(Throwable caught) {
				status.setText("Can not load contest data ");
				caught.printStackTrace();
			}

			@Override
			public void onSuccess(List<ContestInfo> results) {
				System.out.println(results);
				if (results == null || results.size() == 0) {
					status.setText("No contests");
					return;
				}

				for (ContestInfo result : results) {
					System.out.println(result.getName() + result.getFrom()
							+ result.getTo());
					panel.add(new ContestEditorPanelWidget(result.getName(),
							result.getFrom(), result.getTo()));
				}

			}

		});
	}

	class ContestEditorPanelWidget extends HorizontalPanel {

		public ContestEditorPanelWidget(String name, Date from, Date to) {
			setWidth("100%");
			add(new InlineLabel(name));
			if (from != null) {
				add(new InlineLabel(dateToString(from)));
			}
			if (to != null) {
				add(new InlineLabel(dateToString(to)));
			}
			add(new Button("Statistics"));

			setStyleName("formTable");
		}

		public String dateToString(Date d) {

			DateTimeFormat format = DateTimeFormat
					.getFormat("dd.MM.yyyy HH:mm");

			return format.format(d);
		}

	}

}
